package year2023.comparator;


import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeMap;

//比较器
public class Code01_Comparator {

    public static class Student{
        public String name;
        public int id;
        public int age;

        public Student(String name, int id, int age){
            this.name = name;
            this.id = id;
            this.age = age;
        }
    }

    //任何比较器:
    //compare方法里，遵循一个统一的规范:
    //返回负数的时候，认为第一个参数应该排在前面
    //返回正数的时候，认为第二个参数应该排在前面
    //返回0的时候，认为无所谓谁放在前面
    public static class AgeShengOrder implements Comparator<Student> {

        @Override
        public int compare(Student o1, Student o2){
            //升序
//            if (o1.age < o2.age){
//                return -1;
//            }else if (o1.age > o2.age){
//                return 1;
//            }else {
//                return 0;
//            }
            return o1.age - o2.age;
        }
    }

    //根据id从小到大，但是如果id一样，按照年龄从大到小
    public static class IdShengAgeJiangOrder implements Comparator<Student>{

        @Override
        public int compare(Student o1, Student o2){
            return o1.id != o2.id ? (o1.id - o2.id) : (o2.age - o1.age);
        }


    }

    public static void main(String[] args) {
        Student student1 = new Student("A",4,50);
        Student student2 = new Student("B",4,26);
        Student student3 = new Student("C",3,22);

        Student[] students = new Student[]{student1,student2,student3};

        Arrays.sort(students,new IdShengAgeJiangOrder());
        for (int i = 0; i < students.length; i++) {
            Student s = students[i];
            System.out.println(s.name+","+s.id+","+s.age);
        }

        System.out.println("================");

        TreeMap<Student,String> treeMap = new TreeMap<>((a,b) -> a.id - b.id);
    //等同于TreeMap<Student,String> treeMap = new TreeMap<>(new IdShengAgeJiangOrder());
        treeMap.put(student1,"我是学生1，我的名字是A");
        treeMap.put(student2,"我是学生2，我的名字是B");
        treeMap.put(student3,"我是学生3，我的名字是C");

        for (Student s : treeMap.keySet()){
            System.out.println(s.name+","+s.id+","+s.age);
        }
    }







}
